//
//  SZAddImage.m
//  图片选择器
//
//  Created by ios on 16/8/15.
//  Copyright © 2016年 ios. All rights reserved.
//

#import "SZAddImage.h"
#import "BGCangDanController.h"
#import "BGHuoPinZhengShuController.h"
#import "BGFileUpLoadModel.h"
#import "BGfileupload.h"
#import "BGBasicUrl.h"
#import "BGFaBuEntrustController.h"
#import "BGTwoCell.h"

#define imageH 120 // 图片高度
 #define imageW 90 // 图片宽度
 #define kMaxColumn 3 // 每行显示数量
 #define MaxImageCount 9 // 最多显示图片个数
 #define deleImageWH 25 // 删除按钮的宽高
 #define kAdeleImage @"" // 删除按钮图片
 #define kAddImage @"ellipse-2" // 添加按钮图片



 #import "SZAddImage.h"
 @interface SZAddImage()<UINavigationControllerDelegate, UIImagePickerControllerDelegate>
 {
         // 标识被编辑的按钮 -1 为添加新的按钮
         NSInteger editTag;
     NSString *idStr;
     NSString *nameStr;
     NSString *urlStr;
     NSMutableArray *dataArr;
     
     }
 @end

 @implementation SZAddImage

 - (id)initWithFrame:(CGRect)frame
 {
         self = [super initWithFrame:frame];
         if (self) {
                 UIButton *btn = [self createButtonWithImage:kAddImage andSeletor:@selector(addNew:)];
                 [self addSubview:btn];
             dataArr = [NSMutableArray array];
             }
         return self;
     }

 -(NSMutableArray *)images
 {
         if (_images == nil) {
                 _images = [NSMutableArray array];
             }
         return _images;
     }

- (void)click
{
    
    UIAlertController *action = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *a1 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        //拍照
        [self readImageFromCamera];
        
    }];
    [action addAction:a1];
    
    UIAlertAction *a2 = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        //从相册中读取
        [self callImagePicker];
        
    }];
    [action addAction:a2];
    
    UIAlertAction *a3 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [action addAction:a3];
    
    [self.window.rootViewController presentViewController:action animated:YES completion:^{
        
    }];
    
}
- (void)readImageFromCamera {
    
    if ([UIImagePickerController isSourceTypeAvailable:
         UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        imagePicker.delegate = self;
        imagePicker.allowsEditing = YES; //允许用户编辑
        [self.window.rootViewController presentViewController:imagePicker animated:YES completion:nil];
        
    } else {
        //弹出窗口响应点击事件
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"警告" message:@"未检测到摄像头" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alert show];
    }
}

 // 添加新的控件
 - (void)addNew:(UIButton *)btn
 {
         // 标识为添加一个新的图片
    
         if (![self deleClose:btn]) {
                 editTag = -1;
                 [self click];
             }
    
    
     }

 // 修改旧的控件
 - (void)changeOld:(UIButton *)btn
 {
         // 标识为修改(tag为修改标识)
         if (![self deleClose:btn]) {
                 editTag = btn.tag;
                 [self callImagePicker];
             }
     }

 // 删除"删除按钮"
 - (BOOL)deleClose:(UIButton *)btn
 {
         if (btn.subviews.count == 2) {
                 [[btn.subviews lastObject] removeFromSuperview];
                 [self stop:btn];
                 return YES;
             }
    
         return NO;
     }

 // 调用图片选择器
 - (void)callImagePicker
 {
         UIImagePickerController *pc = [[UIImagePickerController alloc] init];
         pc.allowsEditing = YES;
         pc.delegate = self;
         [self.window.rootViewController presentViewController:pc animated:YES completion:nil];
     }


 // 根据图片名称或者图片创建一个新的显示控件
 - (UIButton *)createButtonWithImage:(id)imageNameOrImage andSeletor : (SEL)selector
 {
         UIImage *addImage = nil;
         if ([imageNameOrImage isKindOfClass:[NSString class]]) {
                addImage = [UIImage imageNamed:imageNameOrImage];
        }
         else if([imageNameOrImage isKindOfClass:[UIImage class]])
             {
                     addImage = imageNameOrImage;
                 }
         UIButton *addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
         [addBtn setImage:addImage forState:UIControlStateNormal];
         [addBtn addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside];
         addBtn.tag = self.subviews.count;
    
         // 添加长按手势,用作删除.加号按钮不添加
         if(addBtn.tag != 0)
             {
                 UILongPressGestureRecognizer *gester = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
                 [addBtn addGestureRecognizer:gester];
                 }
         return addBtn;
    
     }


 // 长按添加删除按钮
 - (void)longPress : (UIGestureRecognizer *)gester
 {
         if (gester.state == UIGestureRecognizerStateBegan)
             {
                 UIButton *btn = (UIButton *)gester.view;
            
                 UIButton *dele = [UIButton buttonWithType:UIButtonTypeCustom];
                 dele.bounds = CGRectMake(0, 0, deleImageWH, deleImageWH);
                 [dele setImage:[UIImage imageNamed:kAdeleImage] forState:UIControlStateNormal];
                 [dele addTarget:self action:@selector(deletePic:) forControlEvents:UIControlEventTouchUpInside];
                 dele.frame = CGRectMake(btn.frame.size.width - dele.frame.size.width, 0, dele.frame.size.width, dele.frame.size.height);
            
                 [btn addSubview:dele];
                 [self start : btn];
            
            
                 }
    
     }

 // 长按开始抖动
 - (void)start : (UIButton *)btn {
         double angle1 = -5.0 / 180.0 * M_PI;
         double angle2 = 5.0 / 180.0 * M_PI;
         CAKeyframeAnimation *anim = [CAKeyframeAnimation animation];
         anim.keyPath = @"transform.rotation";
    
         anim.values = @[@(angle1),  @(angle2), @(angle1)];
         anim.duration = 0.25;
         // 动画的重复执行次数
         anim.repeatCount = MAXFLOAT;
    
         // 保持动画执行完毕后的状态
         anim.removedOnCompletion = NO;
         anim.fillMode = kCAFillModeForwards;
    
         [btn.layer addAnimation:anim forKey:@"shake"];
     }

 // 停止抖动
 - (void)stop : (UIButton *)btn{
         [btn.layer removeAnimationForKey:@"shake"];
     }

 // 删除图片
 - (void)deletePic : (UIButton *)btn
 {
     [self.images removeObject:[(UIButton *)btn.superview imageForState:UIControlStateNormal]];
//     NSInteger index = [self.images indexOfObject:[btn imageForState:UIControlStateNormal]];
//     [dataArr removeObjectAtIndex:btn.tag];
         [btn.superview removeFromSuperview];
         if ([[self.subviews lastObject] isHidden]) {
                 [[self.subviews lastObject] setHidden:NO];
             }
    
    
     }

 // 对所有子控件进行布局
 - (void)layoutSubviews
 {
         [super layoutSubviews];
         NSInteger count = self.subviews.count;
         CGFloat btnW = imageW;
         CGFloat btnH = imageH;
         int maxColumn = kMaxColumn > self.frame.size.width / imageW ? self.frame.size.width / imageW : kMaxColumn;
         CGFloat marginX = (self.frame.size.width - maxColumn * btnW) / (count + 1);
         CGFloat marginY = 16;
         for (int i = 0; i < count; i++) {
                 UIButton *btn = self.subviews[i];
                 CGFloat btnX = (i % maxColumn) * (marginX + btnW) + marginX;
                 CGFloat btnY = (i / maxColumn) * (marginY + btnH) + marginY;
                 btn.frame = CGRectMake(btnX, btnY, btnW, btnH);
             }
    
     }

 #pragma mark - UIImagePickerController 代理方法
 -(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
 {
     
    UIImage *image = info[UIImagePickerControllerEditedImage];
   
    NSData *fdate = UIImageJPEGRepresentation(image, 0.1);
     
     BGHuoPinZhengShuController *hp = [BGHuoPinZhengShuController share];
     BGFaBuEntrustController *entrust = [BGFaBuEntrustController share];
     BGTwoCell *cel = [[BGTwoCell alloc] init];
     BGCangDanController *cangdan =[BGCangDanController share];
     
     if (editTag == -1) {
         // 创建一个新的控件
         UIButton *btn = [self createButtonWithImage:image andSeletor:@selector(changeOld:)];
         [self insertSubview:btn atIndex:self.subviews.count - 1];
         [self.images addObject:image];
         if (self.subviews.count - 1 == MaxImageCount) {
             [[self.subviews lastObject] setHidden:YES];
             
         }
     }
     else
     {
         // 根据tag修改需要编辑的控件
         UIButton *btn = (UIButton *)[self viewWithTag:editTag];
         NSInteger index = [self.images indexOfObject:[btn imageForState:UIControlStateNormal]];
         [self.images removeObjectAtIndex:index];
         
         [btn setImage:image forState:UIControlStateNormal];
         [self.images insertObject:image atIndex:index];
         
     }
     
     //图片的上传
    NSString *path = [NSString stringWithFormat:@"%@/Api_1/Index/upload",[BGBasicUrl getBasicUrl]];
    //参数列表（字典类型啊）
     NSDictionary *paramters = @{@"obj_id":@"123",@"type":@"mall"};
    [BGfileupload getFileUpLoadPath:path andParamters:paramters andData:fdate success:^(NSObject *object) {
        
        BGFileUpLoadModel *model = (BGFileUpLoadModel *)object;
        
            if ([model.status isEqualToString:@"1"]) {
             
             NSDictionary *res = [NSDictionary dictionaryWithDictionary:model.res];
             NSArray *arr = [res objectForKey:@"arr"];
             NSDictionary *dic = arr[0];
             nameStr = [dic objectForKey:@"name"];
             urlStr = [dic objectForKey:@"url"];
             idStr = [dic objectForKey:@"id"];

             [dataArr addObject:idStr];
                
                //货品证书的
                if (hp) {
                    hp.imageData = dataArr;

                }
                
                //委托的
                if (entrust) {
                    entrust.imageData = dataArr;

                }
                
                //附加的信息
                if (cel) {
                    if ([_delegate respondsToSelector:@selector(imagesChange:)]) {
                        [_delegate imagesChange:dataArr];
                    }
                }
                
                //仓单的
                if (cangdan) {
                    cangdan.imageArrm = dataArr;
                }
                
                
             
         }else {
             
            
             
         }
         
         
     } failure:^(NSError *error) {
         
     }];
     
    
     
//         if (editTag == -1) {
//                 // 创建一个新的控件
//                 UIButton *btn = [self createButtonWithImage:image andSeletor:@selector(changeOld:)];
//                 [self insertSubview:btn atIndex:self.subviews.count - 1];
//                 [self.images addObject:image];
//                 if (self.subviews.count - 1 == MaxImageCount) {
//                        [[self.subviews lastObject] setHidden:YES];
//            
//                     }
//            }
//        else
//        {
//                     // 根据tag修改需要编辑的控件
//                    UIButton *btn = (UIButton *)[self viewWithTag:editTag];
//                    NSInteger index = [self.images indexOfObject:[btn imageForState:UIControlStateNormal]];
//                     [self.images removeObjectAtIndex:index];
//            
//            [hp.imageData removeObjectAtIndex:index];
//            [cangdan.imageArrm removeObjectAtIndex:index];
//            
//                    [btn setImage:image forState:UIControlStateNormal];
//                    [self.images insertObject:image atIndex:index];
//            
//            [hp.imageData insertObject:idStr atIndex:index];
//            [cangdan.imageArrm insertObject:idStr atIndex:index];
//                }
     
     
//     BGCangDanController *a = [BGCangDanController share];
//     a.imageArrm = self.images;
     
//     hp.imageArrm = self.images;
     
    // 退出图片选择控制器
        [picker dismissViewControllerAnimated:YES completion:nil];
     
     
     
     
}


@end
